import { GlobalState } from "../types/store";
import type { SizeType } from "antd/lib/config-provider/SizeContext";
import { createSlice, PayloadAction, createAsyncThunk } from "@reduxjs/toolkit";
import { defaultLang } from "@/config/config";
import { RouteObject } from "@/routers/types/router";
import { getInfo } from "@/services/api/Login";
import { storage } from "@/utils/Storage";
// 创建异步 action 来获取个人信息
export const getUserInfo = createAsyncThunk("global/getUserInfo", async () => {
	// 发起异步请求获取用户信息
	return await getInfo()
		.then(res => {
			return Promise.resolve(res);
		})
		.catch(() => {
			return Promise.reject("error");
		});
	// const res = await delay(2000, "aaa");
	// return res as string;
});
// promise封装的定时器
function delay(ms: number, data: string) {
	return new Promise(resolve => setTimeout(() => resolve(data), ms));
}
export const updateSystemName = createAsyncThunk<string, string>(
	"global/updateSystemName",
	async (data, config): Promise<string> => {
		console.log(data, config);
		const res = await delay(2000, "aaa");
		return res as string;
	}
);
const globalState: GlobalState = {
	token: storage.getCookie(import.meta.env.VITE_GLOB_TOKEN_KEY) || "",
	userInfo: {
		Info: undefined,
		isLoading: false
	},
	assemblySize: "middle",
	language: defaultLang,
	currentRoute: {},
	themeConfig: {
		primary: "#1890ff",
		isDark: false,
		weakOrGray: ""
	}
};

const globalSlice = createSlice({
	name: "global",
	initialState: globalState,
	reducers: {
		setToken(state: GlobalState, { payload }: PayloadAction<string>) {
			state.token = payload;
		},
		setAssemblySize(state: GlobalState, { payload }: PayloadAction<SizeType>) {
			state.assemblySize = payload;
		},
		setLanguage(state: GlobalState, { payload }: PayloadAction<string>) {
			state.language = payload;
		},
		setDark(state: GlobalState, { payload }: PayloadAction<boolean>) {
			state.themeConfig.isDark = payload;
		},
		setWeakOrGray(state: GlobalState, { payload }: PayloadAction<string>) {
			state.themeConfig.weakOrGray = payload;
		},
		setCurrentRoute(state: GlobalState, { payload }: PayloadAction<RouteObject>) {
			state.currentRoute = payload;
		},
		clearUserInfo(state: GlobalState) {
			state.userInfo = {
				Info: undefined,
				isLoading: false
			};
		}
	},
	extraReducers: builder => {
		builder.addCase(getUserInfo.pending, state => {
			state.userInfo = {
				isLoading: true,
				Info: undefined
			};
		});
		builder.addCase(getUserInfo.fulfilled, (state, action) => {
			state.userInfo = {
				isLoading: false,
				Info: action.payload
			};
		});
		builder.addCase(updateSystemName.fulfilled, (state, action) => {});
	}
});

export const { setToken, setAssemblySize, setLanguage, setDark, setWeakOrGray, setCurrentRoute, clearUserInfo } =
	globalSlice.actions;
export default globalSlice.reducer;
